<script setup lang="ts">
import { axiosRequest } from '@/utils/axiosRequest'
import { computed, onMounted, ref } from 'vue'
import b64ToBlob from 'b64-to-blob'
import { closeToast, showLoadingToast, showToast, type ActionSheetAction } from 'vant'
import { upUserInfo } from '@/stores/channel'
//生日/所在地类型--------------------------------------------------
interface IPickerParams {
  selectedValues: string[]
  selectedOptions: {
    text: string
    value: string
  }[]
  selectedIndexes: number[]
}
const store = upUserInfo()
//头像半模态状态变量------------------------------------------------------
const isShowCamera = ref(false)
//性别半模态状态变量-------------------------------------------------------
const isIntro = ref(false)

//生日弹窗框-----------------------------------------------------
const isShowBirthday = ref(false)
const date = new Date()
//当前日期选中项
const currentDate = ref([
  date.getFullYear().toString(),
  (date.getMonth() + 1).toString(),
  date.getDate().toString(),
])
//拍照上传方法----------------------------------------------
const onClickCamera = async (action: ActionSheetAction, index: number) => {
  if (index == 0) {
    const url = await jky.pickerCamera()
    await uploadImage(url)
    console.log(' 我触发了0 ----->  ', index)
  } else {
    const url = await jky.pickerPhoto()
    await uploadImage(url)
    console.log(' 我触发了1 ----->  ', index)
  }
}

//拍照/相册上传封装--------------------------------------------
const uploadImage = async (imgStr: string) => {
  try {
    isShowCamera.value = false
    showLoadingToast({ message: '正在上传', duration: 0, forbidClick: true })
    const token = jky.queryToken()
    //转换为二进制blob
    const file = b64ToBlob(imgStr, 'image/jpeg')
    // 解析数据
    const fd = new FormData()
    fd.append('photo', file, Date.now() + '.jpeg')
    const res = await axiosRequest<getAvatar, FormData>({
      url: '/user/photo',
      method: 'PATCH',
      headers: {
        Authorization: `Bearer${token.token}`,
        'Content-Type': 'multipart/form-data',
      },
      data: fd,
    })
    userInfo.value.photo = res.data.data.photo
    let user = jky.queryUser()
    user.photo = res.data.data.photo
    jky.updateUser(user)
    getUserInfo()
    showToast('上传成功')
    closeToast()
  } catch (error) {
    console.log('  ----->  ', JSON.stringify(error, null, 2))
  }
}

//是否显示右侧文字方法--------------------------------------
const onShowText = () => {
  jky.onShowText()
}

//选择性别的方法
const onClickIntro = (action: ActionSheetAction, index: number) => {
  isIntro.value = false
  if (index === 0) {
    gender.value = '0'
    updateUserInfo()
  } else {
    gender.value = '1'
    updateUserInfo()
  }
}

//选择生日的方法
const onSelectBirth = ({ selectedValues }: IPickerParams) => {
  isShowBirthday.value = false
  userInfo.value.birthday = selectedValues.join('-')
  updateUserInfo()
}
//切割年月日
const birthday = computed(() => {
  return userInfo.value.birthday.split('-')
})

//-----------------------------------------------------------------
//修改用户信息-------------------------------------------------------
const updateUserInfo = async () => {
  const res = await axiosRequest<null, upUserInfoDate>({
    url: '/user/profile',
    method: 'PATCH',
    data: {
      name: store.nickname,
      gender: gender.value,
      intro: store.intro,
      birthday: userInfo.value.birthday,
    },
  })
  const user = jky.queryUser()
  user.name = store.nickname
  user.intro = store.intro
  user.gender = gender.value
  await jky.updateUser(user)
  await getUserInfo()
  showToast('上传成功')
}
jky.updateUserInfo(updateUserInfo)

//查用户信息
const userInfo = ref({} as UserInfo)
onMounted(() => {
  getUserInfo()
})
const gender = ref<string>(userInfo.value.gender)
const getUserInfo = async () => {
  const token = jky.queryToken()
  const res = await axiosRequest<UserInfo>({
    url: '/user/profile',
    headers: {
      Authorization: `Bearer${token.token}`,
    },
  })
  userInfo.value = res.data.data
  store.nickname = res.data.data.name
  store.intro = jky.queryUser().intro
  userInfo.value.gender = res.data.data.gender
  console.log('  ----->  ', JSON.stringify(res, null, 2))
}

//退出登录
const LogOut = () => {
  jky.LogOut()
}
</script>

<template>
  <div>
    <!-- 头像 -->
    <van-cell
      is-link
      title="头像"
      center
      class="cell-avatar"
      @click="isShowCamera = true"
      :clickable="true"
    >
      <template #value>
        <div class="avatar-container">
          <van-image round width="30px" height="30px" :src="userInfo.photo" />
        </div>
      </template>
    </van-cell>

    <!-- 昵称 -->
    <van-cell
      is-link
      title="昵称"
      :value="userInfo.name"
      to="/nickName"
      class="cell-avatar"
      @click="onShowText"
    >
    </van-cell>

    <!-- 简介 -->
    <van-cell
      is-link
      title="简介"
      class="cell-avatar"
      to="/intro"
      @click="onShowText"
      :value="store.intro"
    ></van-cell>
  </div>

  <div class="van-Height">
    <div>
      <!-- 性别 -->
      <van-cell
        is-link
        title="性别"
        :value="userInfo.gender == '0' ? '男' : '女'"
        @click="isIntro = true"
      >
      </van-cell>

      <!-- 生日 -->
      <van-cell is-link title="生日" @click="isShowBirthday = true" :value="userInfo.birthday">
      </van-cell>
    </div>
    <div>
      <van-button
        color="linear-gradient(to right, #ff6034, #ee0a24)"
        style="width: 100%"
        class="button-container"
        @click="LogOut"
      >
        退出登录
      </van-button>
    </div>
  </div>

  <!-- 修改头像弹窗框 -->
  <VanActionSheet
    v-model:show="isShowCamera"
    @select="onClickCamera"
    :actions="[{ name: '拍照' }, { name: '相册' }]"
    cancel-text="取消"
  />

  <!-- 选择性别 -->
  <VanActionSheet
    v-model:show="isIntro"
    @select="onClickIntro"
    :actions="[{ name: '男' }, { name: '女' }]"
    cancel-text="取消"
  />

  <!-- 选择生日 -->
  <VanPopup v-model:show="isShowBirthday" position="bottom">
    <VanDatePicker
      title="请选择生日"
      :min-date="new Date('1900-01-01')"
      :max-date="new Date()"
      :model-value="birthday"
      @cancel="isShowBirthday = false"
      @confirm="onSelectBirth"
    />
  </VanPopup>
</template>

<style scoped>
* {
  padding: 0px;
  margin: 0px;
  box-sizing: border-box;
}
.cell-avatar {
  height: 44px;
}

.avatar-container {
  display: flex;
  align-items: center;
  justify-content: end;
}

.van-cell {
  padding: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.van-Height {
  margin-top: 10px;
  height: 140vw;
  background-color: white;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.van-cell:last-child {
  border-bottom: none;
}

.button-container {
  display: flex;
  justify-content: center;
}
</style>
